import math
from datetime import datetime
import codecs
from flask_wtf.file import FileRequired, FileAllowed

from app.libs.ParseDocx import ParseDocx, ParseDoc, ParsePDF
from app.config.secure import DOC_PATH, SELFDOC_PATH
from app.libs.token_auth import parseToken
from app.models.aigc_order_info import aigc_order_info
from app.models.order_info import order_info
from app.models.user import User
from app.models.writer_orders import writer_orders
from app.taobao_api.get_order_status import Order_Status
from app.validators.base import BaseForm as Form, SearchForm
from wtforms import StringField, IntegerField, FloatField, FieldList, TextField, TextAreaField, FileField
from wtforms.validators import length, DataRequired, Length, ValidationError
from app import redisclient

class AIGCArticleSubmitForm(Form):
    title = StringField(default='')
    author = StringField(default='佚名', validators=[length(min=0, max=48, message='作者长度不能超过50字')])
    content = TextAreaField(default='')
    order_number = StringField()
    chars_sum = IntegerField()
    sum = IntegerField()
    taobao_orders = []
    domain = StringField(default='')
    free = IntegerField(default=0)
    file_path = StringField(default='')
    token = StringField(default='')
    uid = IntegerField(default=0)

    def validate_order_number(self, field):
        if self.token.data and self.token.data != '':
            self.uid.data = parseToken(self.token.data)
        if self.content.data == '':
            raise ValidationError('没有获取到内容，请重新提交')
        if self.chars_sum.data == 0:
            self.chars_sum.data = len(self.content.data)
        unit = 1000
        sum = math.floor(int(self.chars_sum.data) / unit)
        if sum == 0:
            sum = 1
        self.sum.data = sum
        self.taobao_orders = field.data.split(',') if ',' in field.data else [field.data]
        secret = redisclient.getAppSecret(self.domain.data) if self.domain.data != '' else redisclient.getAppSecret(
                'check')
        if len(set(self.taobao_orders)) != len(self.taobao_orders):
            raise ValidationError('请不要重复输入相同订单号哦。')
        order_status = Order_Status(field.data, self.sum.data, secret, self.chars_sum.data)
        isvalid = order_status.validate_order_number('aigc')
        if isvalid == 9:
            self.free.data = 1
            
class WriterAIGCArticleSubmitForm(Form):
    title = StringField(default='')
    author = StringField(default='佚名', validators=[length(min=0, max=48, message='作者长度不能超过50字')])
    content = TextAreaField(default='')
    order_number = StringField()
    
    def validate_order_number(self, field):
        unfinished = aigc_order_info.query.filter_by(taobao_orders=field.data).filter_by(completed=0).first()
        if unfinished:
            raise ValidationError('您存在正在进行的检测任务,请稍后提交')
